import Bg from '../components/home/Bg'
import store from '../store/index'
import Page from '../components/base/page'
import StartButton from '../components/home/start-buton'
import Music from '../store/music'
import { getCanvas, getCtx } from '../../ctx'
import music from '../store/music'
import Event from '../event/index'
import router from '../route/index'

/**
 * home页
 */
export default class Home extends Page {
  constructor(ctx = getCtx()) {
    super(ctx)
    this.restart()
    Event.on('start-game', () => {
      router.push('coins')
    })
  }

  restart() {
    this.bg = new Bg()
    // this.startButton = new StartButton()
    this.appendChild(this.bg)
    // this.addEvent('touchend', () => {
    //   this.startButton.isDown = false
    // })
    
    this.$onShow(() => {
      Music.setAudio({
        name: 'HomeBgm',
        play: true,
        autoplay: true,
        volume: 0.08
      })
      const loop = () => {
        Music.HomeBgm.onEnded(() => {
          Music.updateMusic('HomeBgm')
          Music.HomeBgm.play()
          Music.HomeBgm.volume = 0.08
          loop()
        })
      }
      loop()
    })
    this.$onHide(() => {
      Music.pause('HomeBgm')
    })
    this.$destroy(() => {
      Music.pause('HomeBgm')
    })
  }
  
  /**
   * canvas重绘函数
   * 每一帧重新绘制所有的需要展示的元素
   */
  render() {
    const ctx = getCtx()
    ctx.clearRect(0, 0, getCanvas().width, getCanvas().height)
    this.renderChildren(ctx)

  }

  // 游戏逻辑更新主函数
  update() {
    if (store.gameOver) return
    this.updateChildren()
  }
}
